﻿using D.Wx.Dtos;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace D.Wx
{
    /// <summary>
    /// 微信接口请求方法
    /// </summary>
    public static class WxRequest<T> where T : ErrorMessage
    {
        /// <summary>
        /// Get请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <returns></returns>
        public static T Get(string url)
        {
            HttpWebRequest ApiRequest = (HttpWebRequest)WebRequest.Create(url);
            ApiRequest.Method = "GET";//post方式
            ApiRequest.Accept = "text/html, application/xhtml+xml, */*";
            ApiRequest.ContentType = "application/x-www-form-urlencoded";
            HttpWebResponse response = (HttpWebResponse)ApiRequest.GetResponse();
            T TResponse = default(T);
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
            {
                string jsonStr = reader.ReadToEnd();
                TResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonStr);
            }
            return TResponse;
        }
         
        /// <summary>
        /// POST请求
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="url"></param>
        /// <param name="poststr"></param>
        /// <returns></returns>
        public static T Post(string url, string poststr)
        {
            HttpWebRequest ApiRequest = (HttpWebRequest)WebRequest.Create(url);
            ApiRequest.Method = "POST";//post方式
            ApiRequest.Accept = "text/html, application/xhtml+xml, */*";
            ApiRequest.ContentType = "application/x-www-form-urlencoded";
            if (!string.IsNullOrEmpty(poststr))
            {
                byte[] buffer = Encoding.UTF8.GetBytes(poststr);
                ApiRequest.ContentLength = buffer.Length;
                ApiRequest.GetRequestStream().Write(buffer, 0, buffer.Length);
            }
            HttpWebResponse response = (HttpWebResponse)ApiRequest.GetResponse();
            T TResponse = default(T);
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
            {
                string jsonStr = reader.ReadToEnd();
                TResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<T>(jsonStr);
            }
            return TResponse;
        }
    }
}
